const {
  initPicker,
  yearsArr,
  monthsArr,
  daysArr,
  hoursArr,
  minsArr,
  secondsArr,
  formatTime3
} = require("../../utils/util");

const initValue = initPicker();
console.log('initvalue', initValue);

// components/ActionSheet/index.js
Component({
  /*** 组件的属性列表 */
  properties: {
    title: {
      type: String,
      value: '选择时间'
    }
  },

  /*** 组件的初始数据 */
  data: {
    years: yearsArr,
    months: monthsArr,
    days: daysArr,
    hours: hoursArr,
    mins: minsArr,
    seconds: secondsArr,
    value: initValue,
    isDaytime: true,
    curSelect: 0, // 0 开始时间   1 结束时间 
    picker: [], //  记录时间
    pickerCache: formatPicker(initValue), // 时间缓存区
    show: false,
    actions: [],
    success: function () {},
    error: function () {}
  },

  /*** 组件的方法列表 */
  methods: {
    open(options = {}) {
      const {
        actions = [],
          success = () => {},
          error = () => {}
      } = options;

      //  打开弹窗之前将数据进行修改成当前的时间

      this.setData({
        actions,
        success,
        error
      }, () => {
        this.setData({
          show: true
        })
      });
    },
    close() {
      this.setData({
        show: false
      });
    },
    onSelect(event) {
      const {
        index
      } = event.currentTarget.dataset;
      this.setData({
        curSelect: index
      });
    },
    //  点击确定按钮
    onDefine() {
      this.setData({
        picker: this.data.pickerCache
      });
      this.data.success( setResult.call(this) );
      this.close();
    },
    bindChange(e) {
      const val = e.detail.value;
      formatDay.call(this, val);
      //  缓存数据，便于后期对其进行处理
      this.setData({ pickerCache: formatPicker(val)})
    }
  }
})

//  处理返回值
function setResult() {
  const arr = this.data.picker;
  const str = formatTime3(arr);
  
  return {
    name: str,
    code: str
  }
}

//  处理日期的天数，每个月份都会有差距
function formatDay(arr) {
  const year = arr[0] + 1000;
  const month = arr[1] + 1;
  var daycount = new Date(year, month, 0).getDate();
  const days = addDay(daycount);
  //  修改 days 的天数
  this.setData({
    days
  });
}

function formatPicker(arr) {
  const year = arr[0] + 1000;
  const month = arr[1] + 1;
  const day = arr[2] + 1;
  const hour = arr[3];
  const min = arr[4];
  const second = arr[5];
  return [year, month, day, hour, min, second];
}

//  添加day
function addDay(num) {
  const arr = [];
  for (let i = 1; i <= num; i++) {
    arr.push(i);
  }
  return arr;
}
